package com.itheima.stock.common;

import com.itheima.stock.ex.CustomerException;
import com.itheima.stock.vo.resp.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @ClassName GlobalExceptionHandler
 * @Description TODO
 * @Author Zack
 * @Date 2022/12/5 19:52
 * @Version 1.0
 */
@Slf4j
@RestControllerAdvice()
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R exceptionHandler(MethodArgumentNotValidException e) {
        String err = e.getBindingResult().getFieldError() != null ?
                e.getBindingResult().getFieldError().getDefaultMessage() :
                e.getMessage();
        log.error("err = " + err);
        return R.error(err);
    }

    @ExceptionHandler(CustomerException.class)
    public R exceptionHandler(CustomerException e) {
        log.error("err = " + e);
        return R.error(e.getMessage());
    }

}
